<template>
  <BasicDrawer v-bind="$attrs" @register="register" title="油站详细情况" width="50%">
    <a-table :columns="columns" :data-source="data" :expanded-row-keys="expandedRowKeys" @expand="handleExpand" class="components-table-demo-nested">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'claimStatus'">
          {{ getStatusText(record.claimStatus) }}
        </template>
        <template v-else-if="column.key === 'position'">
          {{ getPositionText(record.position) }}
        </template>
      </template>
      <template #expandedRowRender="{ record }">
        <a-table :columns="innerColumns" :data-source="record.children" :pagination="false">
          <template #bodyCell="{ column, record: childRecord }">
            <template v-if="column.dataIndex === 'claimStatus'">
              {{ getStatusText(childRecord.claimStatus) }}
            </template>
            <template v-else-if="column.dataIndex === 'position'">
              {{ getPositionText(childRecord.position) }}
            </template>
          </template>
        </a-table>
      </template>
    </a-table>
  </BasicDrawer>
</template>

<script lang="ts">
  import { defineComponent, ref, onMounted } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { Table, Badge, Dropdown, Menu } from 'ant-design-vue';
  import { getDevices } from '/@/api/sys/user';

  interface DataItem {
    key: string;
    address: string;
    checkDate: string;
    company: string;
    createBy: string;
    createTime: string;
    children: ChildDataItem[];
  }

  interface ChildDataItem {
    id: string;
    createBy: string;
    createTime: string;
    updateBy: string;
    code: string;
    madeInCompany: string;
    region: string;
    claimStatus: number;
    position: number;
  }

  export default defineComponent({
    components: { BasicDrawer, ATable: Table, ABadge: Badge, ADropdown: Dropdown, AMenu: Menu },
    setup() {
      const receivedData = ref<DataItem | null>(null); // 用于存储接收到的数据
      const data = ref<DataItem[]>([]);
      const expandedRowKeys = ref<string[]>([]);
      const sondata = ref<ChildDataItem[]>([]);
      const handleExpand = (expanded: boolean, record: DataItem) => {
        console.log('Expanded: ', expanded, 'Record: ', record);

        if (expanded) {
          expandedRowKeys.value = [record.key];
        } else {
          expandedRowKeys.value = [];
        }
      };

      const getStatusText = (status: number): string => {
        switch (status) {
          case 1:
            return '待领取';
          case 2:
            return '已领用';
          case 3:
            return '已施封';
          case 4:
            return '已拆封';
          case 5:
            return '已报损损失';
          case 6:
            return '已报废';
          default:
            return '未知状态';
        }
      };

      const getPositionText = (position: number): string => {
        switch (position) {
          case 1:
            return '编码器';
          case 2:
            return '流量计';
          case 3:
            return '主板';
          default:
            return '未知位置';
        }
      };

      const columns = [
        { title: '地址', dataIndex: 'address', key: 'address' },
        { title: '检查日期', dataIndex: 'checkDate', key: 'checkDate' },
        { title: '公司', dataIndex: 'company', key: 'company' },
        { title: '创建人', dataIndex: 'createBy', key: 'createBy' },
        { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
        { title: '状态', dataIndex: 'claimStatus', key: 'claimStatus' },
        { title: '施封位置', dataIndex: 'position', key: 'position' },
      ];

      const innerColumns = [
        { title: '设备号', dataIndex: 'id', key: 'id' },
        { title: '检查日期', dataIndex: 'checkDate', key: 'checkDate' },
        { title: '状态', dataIndex: 'claimStatus', key: 'claimStatus' },
        { title: '施封位置', dataIndex: 'position', key: 'position' },
        { title: '所属部门', dataIndex: 'sysOrgCode', key: 'sysOrgCode' },
        { title: '所属区县', dataIndex: 'region', key: 'region' },
      ];

      const [register] = useDrawerInner((data) => {
        // 在抽屉打开时接收数据
        receivedData.value = data; // 存储数据
        console.log('Received data in drawer:', receivedData.value);
        fetchData({
          company: receivedData.value.company,
          regionCode: receivedData.value.regionCode,
        });
      });

      const fetchData = async (params: { company: string; regionCode: string }) => {
        try {
          const response = await getDevices(params); // 假设 getDevices 接受 params 参数
          const newData = response; // 假设响应数据在 response.data 中
          console.log('API Response:', response);
          newData.forEach((item, index) => {
            item.key = `parent-${index}-${item.id}`; // 使用 item.id 生成唯一 key
            item.children?.forEach((child, childIndex) => {
              child.key = `child-${index}-${childIndex}-${child.id}`; // 使用 child.id 生成唯一 key
            });
          });

          data.value = newData; // 更新数据
        } catch (error) {
          console.error('Failed to fetch data:', error);
        }
      };

      onMounted(() => {
        if (receivedData.value) {
          fetchData({
            company: receivedData.value.company,
            regionCode: receivedData.value.regionCode,
          });
        }
      });

      return { register, data, columns, innerColumns, expandedRowKeys, handleExpand, getStatusText, getPositionText };
    },
  });
</script>

<style scoped>
  .components-table-demo-nested .ant-table-tbody .ant-table-expanded-row {
    margin-bottom: 16px;
  }
  .table-operation a {
    margin-right: 8px;
  }
</style>
